package com.aistar.util;

import java.io.IOException;
import java.io.Serializable;
import java.util.concurrent.ConcurrentHashMap;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;

@ServerEndpoint("/message/{customerId}")
@Component
public class WebSocketServerUtil {

    private static Log log = LogFactory.getLog(WebSocketServerUtil.class);
    // concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
    private static ConcurrentHashMap<Integer, WebSocketServerUtil> webSocketMap = new ConcurrentHashMap<>();

    private Session session; // 与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Integer customerId;

    @OnOpen // 连接建立成功调用的方法
    public void onOpen(Session session, @PathParam("customerId") Integer customerId) {
        this.session = session;
        this.customerId = customerId;
        webSocketMap.put(customerId, this); // 加入set中
    }

    @OnMessage // 收到客户端消息后调用的方法
    public void onMessage(String message, Session session) {
        log.info("用户消息:" + customerId + ",报文:" + message);
        //可以群发消息
        //消息保存到数据库、redis
        if (StringUtils.isNotBlank(message)) {
            try {
                //解析发送的报文
                JSONObject jsonObject = JSON.parseObject(message);
                //追加发送人(防止串改)
                jsonObject.put("fromUserId", this.customerId);
                Integer toUserId = Integer.valueOf(jsonObject.getString("toUserId"));
                //传送给对应toUserId用户的websocket
                if (webSocketMap.containsKey(toUserId))
                    webSocketMap.get(toUserId).sendMessage(jsonObject.toJSONString());
                else
                    log.error("请求的customerId:" + toUserId + "不在该服务器上");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }

    @OnClose // 连接关闭调用的方法
    public void onClose() {
        webSocketMap.remove(customerId);
    }


    /**
     * 实现服务器主动推送
     */
    private void sendMessage(Serializable bean) throws IOException {
        this.session.getBasicRemote().sendText(JSON.toJSONString(bean));
    }


    /**
     * 发送自定义消息
     */
    public static void sendInfo(@PathParam("customerId") Integer customerId, Serializable bean) {
        if (customerId != null && webSocketMap.containsKey(customerId)) {
            try {
                webSocketMap.get(customerId).sendMessage(bean);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 发送自定义消息
     */
    public static void sendInfo(@PathParam("customerId") Integer customerId) {
        if (customerId != null && webSocketMap.containsKey(customerId)) {
            try {
                webSocketMap.get(customerId).sendMessage(null);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    public static int getOnlineCount() {
        return webSocketMap.size();
    }
}
